/**
 * @author：小小游 - allen
 * @description：微信接口统一封装处理
 */
const request = require('request');
let config = require('../config/pay_info');
config = config.wx;
const util = require('../utils/util');
// 获取网页授权的access_token
const getAccessToken = code => { 
    let token_url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${config.APP_ID}&secret=${config.APP_SECRET}&code=${code}&grant_type=authorization_code`;
    return new Promise((resolve, reject) => {
        request.get(token_url, (err, response, body) => {
            let result = util.handleResponse(err, response, body);
            resolve(result);
        });
    });
};

// 获取用户信息
const getUserInfo = (access_token, code) => { 
    let url = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${code}&lang=zh_CN`;
    return new Promise((resolve, reject) => {
        request.get(url, (err, response, body) => {
            let result = util.handleResponse(err, response, body);
            resolve(result);
        });
    });
};

// 获取用户基础token
const getBasicToken = () => { 
    let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.APP_ID}&secret=${config.APP_SECRET}`;
    return new Promise((resolve, reject) => {
        request.get(url, (err, response, body) => {
            let result = util.handleResponse(err, response, body);
            resolve(result);
        });
    });
};

// 通过基础的access_token获取到用户授权的票据jsapi_ticket
const getJSAPITicket = token => { 
    let url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`;
    return new Promise((resolve, reject) => {
        request.get(url, (err, response, body) => {
            let result = util.handleResponse(err, response, body);
            resolve(result);
        });
    });
};

module.exports = {
    getAccessToken,
    getUserInfo,
    getBasicToken,
    getJSAPITicket
};